<?php
class Message extends AppModel {

	var $name = 'Message';

	//The Associations below have been created with all possible keys, those that are not needed can be removed
	var $belongsTo = array(
			'From' => array('className' => 'User',
								'foreignKey' => 'from_id',
								'conditions' => '',
								'fields' => '',
								'order' => ''
			),
			'To' => array('className' => 'User',
								'foreignKey' => 'to_id',
								'conditions' => '',
								'fields' => '',
								'order' => ''
			),
	);


	function paginateConditions($dir, $uid) {
		$c = array($dir. '_id'=> $uid, 'del_'. $dir=>0);
		return array('conditions'=>$c, 'recursive'=>2, 'limit'=>10, 'order'=>array('status', 'created'));
	}


	function sendMessage($data) {
		$send = false;

		if (!empty($data['Message']['text'])) {
			//if ($data['Message']['from_id'] != $data['Message']['to_id']) {
				$send = true;
			//}
		}

		if ($send) {
			$this->create();
			return $this->save($data);
		}
	}

	function changeStatus($id, $status) {
		$this->id = $id;
		$this->saveField('status', $status);
	}

	function countMessage($uid, $status) {
		$c = array('to_id'=>$uid, 'status'=>$status);
		return $this->find('count', array('conditions'=>$c));
	}

	function deleteMessage($id, $uid) {
		$delete = $return = $dir = false;
		$c = array('id'=>$id, 'or'=>array('from_id'=>$uid, 'to_id'=>$uid));
		$f = array('from_id', 'to_id', 'id', 'del_to', 'del_from');
		$m = $this->find('first', array('conditions'=>$c, 'fields'=>$f, 'recursive'=>-1));
		
		if ($m) {
			$m = $m['Message'];
			if ($m['from_id'] === $uid) {
				$dir = 'from';
			} elseif ($m['to_id'] === $uid) {
				$dir = 'to';
			}

		}

		if ($dir) {
			if (($dir === 'from' && $m['del_to']) || ($dir === 'to' && $m['del_from']) || ($m['to_id'] === $m['from_id'])) {
				$delete = true;
			} 

			if ($delete) {
				$this->id = $id;
				$return = $this->del();
			} else {
				$delkey = 'del_'.$dir;
				if (!$m[$delkey]) {
					$this->id = $id;
					$return = $this->save(array($delkey=>1));
				}
			}
		}
		
		return $return;
	}

}
?>
